package com.ydc.ln.tutorial.httpclient.test;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * <pre>
 * 依赖jar包
 * httpclient-4.1.2.jar
 * httpcore-4.1.2.jar
 * commons-logging-1.1.1.jar
 * </pre>
 * 
 * @author yangdc
 * 
 */
public class HttpClientUtil {
	/**
	 * 用get方法访问指定url并返回内容
	 */
	public static String visitByGet(String url) {
		String content = "";
		// 创建默认的httpClient实例
		HttpClient httpClient = new DefaultHttpClient();
		try {
			// 创建httpGet
			// http://www.88web.org/css-templates.htm http://www.baidu.com
			HttpGet httpGet = new HttpGet(url);
			System.out.println("executing request " + httpGet.getURI());

			// 查看默认request头部信息
			System.out.println("Accept-Charset:" + httpGet.getFirstHeader("Accept-Charset"));
			// 以下这条如果不加会发现无论你设置Accept-Charset为gbk还是utf-8，他都会默认返回gb2312（本例针对google.cn来说）
			// httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)");
			// 用逗号分隔显示可以同时接受多种编码
			// httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
			// httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
			// httpGet.setHeader("Accept-Charset", "UTF-8;q=0.7,*;q=0.7");
			// 验证头部信息设置生效
			// System.out.println("Accept-Charset:" + httpGet.getFirstHeader("Accept-Charset").getValue());

			// 执行get请求
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			System.out.println("--------------------------------------------");
			// 打印响应状态
			System.out.println(response.getStatusLine());
			System.out.println(response.getStatusLine().getProtocolVersion());
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(response.getStatusLine().getReasonPhrase());
			if (entity != null) {
				// 打印响应长度
				// System.out.println("Response content length: " + entity.getContentLength());
				// 打印响应内容
				content = EntityUtils.toString(entity, "UTF-8");
				System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
			}
			System.out.println("--------------------------------------------");
		} catch (ClientProtocolException ce) {
			ce.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接，释放资源
			httpClient.getConnectionManager().shutdown();
		}
		return content;
	}
}
